package com.nutiteq.mapper.forms;

import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.TextField;

import com.nutiteq.mapper.MapScreen;
import com.nutiteq.mapper.Mapper;

public class SetLocationForm extends Form implements CommandListener {
  public static final Command SET_MAP_COMPONENT_LOCATION = new Command("Change screen pos.",
      Command.ITEM, 0);
  private final int minX;
  private final int minY;
  private final int maxX;
  private final int maxY;
  private final MapScreen mapScreen;

  private static final Command BACK = new Command("Back", Command.BACK, 0);
  private static final Command MOVE = new Command("Move", Command.ITEM, 0);

  private TextField newX;
  private TextField newY;

  public SetLocationForm(final int minX, final int minY, final int maxX, final int maxY,
      final MapScreen mapScreen) {
    super("Set location on screen");
    this.minX = minX;
    this.minY = minY;
    this.maxX = maxX;
    this.maxY = maxY;
    this.mapScreen = mapScreen;
    newX = new TextField("Component location x on screen (" + minX + " - " + maxX + ")", Integer
        .toString(minX), Integer.toString(maxX).length(), TextField.ANY);
    newY = new TextField("Component location y on screen (" + minY + " - " + maxY + ")", Integer
        .toString(minY), Integer.toString(maxY).length(), TextField.ANY);

    append(newX);
    append(newY);

    addCommand(BACK);
    addCommand(MOVE);
    setCommandListener(this);
  }

  public void commandAction(final Command cmd, final Displayable d) {
    if (cmd == BACK) {

    } else if (cmd == MOVE) {
      final int xTmp = parseInt(newX.getString(), minX);
      final int yTmp = parseInt(newY.getString(), minY);
      mapScreen.setPaintLocation(xTmp >= minX && xTmp <= maxX ? xTmp : minX, yTmp >= minY
          && yTmp <= maxY ? yTmp : minY);
    }
    Display.getDisplay(Mapper.instance).setCurrent(MapScreen.instance);
  }

  private int parseInt(final String numberString, final int defaultValue) {
    int result = defaultValue;
    try {
      result = Integer.parseInt(numberString);
    } catch (NumberFormatException e) {
    }

    return result;
  }
}
